package Talk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author shkstart
 * @creat 2022-05-15:25
 */
public class ChatClient {
    //创建发送消息线程池对象
    private static final ExecutorService sendMsgThreadPool =
            Executors.newSingleThreadExecutor();
    //创建接受消息线程池对象
    private static final ExecutorService receiveMsgThreadPool =
            Executors.newSingleThreadExecutor();
    //创建扫描器对象
    private static Scanner input = new Scanner(System.in);

    /**
     * 启动客户端
     * @param serverIP
     * @param serverPort
     */
    private static void startChatRoomClient(String serverIP,int serverPort){

        try {
            Socket socketClient=   new Socket(serverIP,serverPort);
            //向服务器发送消息线程池
            sendMsgThreadPool.execute(()->{
                try {
                    PrintStream ps = new PrintStream(socketClient.getOutputStream());
                    String line = "";
                    while ((line = input.nextLine()) != null) {
                        ps.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
            //接受服务器响应线程池
            receiveMsgThreadPool.execute(()->{
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            socketClient.getInputStream()));
                    // 按行接收信息
                    String line = "";
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 程序入口
     * @param args
     */
    public static void main(String[] args) {
        startChatRoomClient(Constants.SERVER_IP_ADDRESS,Constants.SERVER_PORT);
    }
}
